<template>
  <div @drop="drop" @dragover="allowDrop" :id="withKeyId" class="dmap-container"></div>
</template>
<script setup>
/**
 * 地图渲染组件
 */
import { computed, onUnmounted, onMounted, h, ref, toRaw } from "vue"
import { getQueryString } from "@/utils/mars-util"
import { getDefaultContextMenu } from "@/utils/getDefaultContextMenu"
import { $alert, $message } from "@/components/mars-ui"
import { useStore } from "vuex"
import { useLayer } from "@/common/uses/use-layer"
import { mountToWindow } from "@/components/de-work/map"

const store = useStore()

const props = defineProps({
  mapKey: String,
  options: Object,
  isMainViewer: Boolean
})

// 用于存放地球组件实例
let viewer // 地图对象

// 使用用户传入的 mapKey 拼接生成 withKeyId 作为当前显示容器的id
const withKeyId = computed(() => `dmap-container-${props.mapKey}`)

const allowDrop = (e) => {
  e.preventDefault()
}

/**
 * 视图上触发拖拽事件，全局广播
 * @param e
 */

const setDropEvent = (e) => store.commit("event/SET_DropEvent", e)

const drop = (e) => {
  setDropEvent(e)
  e.preventDefault()
}

onMounted(() => {
  // 获取配置
  const target = props.isMainViewer ? window.$config?.global : window.$config?.lesser
  const options = target?.viewerOption || {}
  DE.ready({}).then(initDmap(options))
})

// onload事件将在地图渲染后触发
const emit = defineEmits(["onload"])
const initDmap = (option) => {
  // viewer 的基础配置
  option = DE.Util.merge(option, toRaw(props.options)) // 合并配置
  viewer = new DE.Viewer(withKeyId.value, {
    contextOptions: {
      requestWebgl1: true
    }
  })
  // 右键菜单全局挂载到viewer对象上的plot图层
  viewer.plotLayer = useLayer("initPlotLayer", { viewer })
  viewer.setOptions(option)
  mountToWindow({ [`${props.mapKey}`]: viewer })

  // map基础配置
  initMapBaseConfig(viewer)

  // map构造完成后的一些处理
  onMapLoad()

  emit("onload", viewer)
}

/**
 * 底图的基础配置
 * @param viewer
 */
function initMapBaseConfig(viewer) {
  // const baseLayer = DE.ImageryLayerFactory.createImageryLayer(DE.ImageryType.SINGLE_TILE, {
  //   url: "img/tile/world_img.jpg"
  // })
  // viewer.addBaseLayer(baseLayer)
  // 如果有xyz传参，进行定位
  const lat = getQueryString("lat")
  const lng = getQueryString("lng")
  if (lat && lng) {
    viewer.flyToPosition(new DE.Position(lng, lat, 100, 0, -90), null, 0)
  }

  // 右下角底图切换组件
  viewer.mapSwitch.enable = true
  // 开启右键菜单
  viewer.contextMenu.enable = true
  // 绑定当前项目的默认右键菜单
  viewer.contextMenu.DEFAULT_MENU = getDefaultContextMenu(DE, viewer)

  // 底图添加
  addBaseMaps()

  // 添加位置组件
  viewer.locationBar.enable = true
  // 添加比例尺
  viewer.distanceLegend.enable = true
}

function addBaseMaps() {
  // 如果有基础图层配置
  if (window.$config?.global?.baseMap) {
    window.$config.global.baseMap.forEach((item) => {
      const baseLayer_img = DE.ImageryLayerFactory.createImageryLayer(item.type, {
        url: item.mapOption.url,
        fileExtension: item.mapOption.fileExtension || "png"
      })
      viewer.addBaseLayer(baseLayer_img, {
        iconUrl: item.baseLayerOption.iconUrl,
        name: item.baseLayerOption.name
      })
    })
  } else {
    // 否则默认使用离线地图
    const baseLayer = DE.ImageryLayerFactory.createImageryLayer(
      DE.ImageryType.SINGLE_TILE,
      {
        url: "img/tile/world_img.jpg"
      }
    )
    viewer.addBaseLayer(baseLayer)
  }
}

// map构造完成后的一些处理
function onMapLoad() {
  // dmap地图内部使用，如右键菜单弹窗
  // @ts-ignore
  window.globalAlert = $alert
  // @ts-ignore
  window.globalMsg = $message

  window.showPopupDetails = (item) => {
    $alert(item.NAME)
  }
}

// 组件卸载之前销毁dmap实例
onUnmounted(() => {
  if (viewer) {
    viewer.off(DE.MouseEventType.CLICK)
    viewer.off(DE.MouseEventType.RIGHT_CLICK)
    viewer.off(DE.MouseEventType.WHEEL)
    viewer.destroy()
    viewer = null
  }
  console.log("map销毁完成", viewer)
})
</script>

<style lang="less">
.dmap-container {
  position: relative;
  width: 100%;
  height: 100%;
}

/**cesium 工具按钮栏*/
.cesium-viewer-toolbar {
  top: auto !important;
  bottom: 35px !important;
  left: 12px !important;
  right: auto !important;
}

.cesium-toolbar-button img {
  height: 100%;
}

.cesium-viewer-toolbar > .cesium-toolbar-button,
.cesium-navigationHelpButton-wrapper,
.cesium-viewer-geocoderContainer {
  margin-bottom: 5px;
  float: left;
  clear: both;
  text-align: center;
}

.cesium-button {
  background-color: rgba(23, 49, 71, 0.7);
  color: #e6e6e6;
  fill: #e6e6e6;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
  line-height: 32px;
}

.cesium-button:hover {
  background-color: rgba(0, 138, 255, 0.7);
}

/**cesium 底图切换面板*/
.cesium-baseLayerPicker-dropDown {
  bottom: 0;
  left: 40px;
  max-height: 700px;
  margin-bottom: 5px;
  background-color: rgba(23, 49, 71, 0.7);
}

/**cesium 帮助面板*/
.cesium-navigation-help {
  top: auto;
  bottom: 0;
  left: 40px;
  transform-origin: left bottom;
  background: none;
  background-color: rgba(23, 49, 71, 0.8);

  .cesium-navigation-help-instructions {
    background: none;
  }

  .cesium-navigation-button {
    background: none;
  }

  .cesium-navigation-button-selected,
  .cesium-navigation-button-unselected:hover {
    background-color: rgba(23, 49, 71, 1);
  }
}

/**cesium 二维三维切换*/
.cesium-sceneModePicker-wrapper {
  width: auto;
}

.cesium-sceneModePicker-wrapper .cesium-sceneModePicker-dropDown-icon {
  float: right;
  margin: 0 3px;
}

/**cesium POI查询输入框*/
.cesium-viewer-geocoderContainer .search-results {
  left: 0;
  right: 40px;
  width: auto;
  z-index: 9999;
}

.cesium-geocoder-searchButton {
  background-color: rgba(23, 49, 71, 0.8);
}

.cesium-viewer-geocoderContainer .cesium-geocoder-input {
  background-color: rgba(63, 72, 84, 0.7);
}

.cesium-viewer-geocoderContainer .cesium-geocoder-input:focus {
  background-color: var(--mars-bg-base, rgba(63, 72, 84, 0.9));
}

.cesium-viewer-geocoderContainer .search-results {
  background-color: rgba(23, 49, 71, 0.8);
}

/**cesium info信息框*/
.cesium-infoBox {
  top: 50px;
  background: var(--mars-bg-base, rgba(63, 72, 84, 0.9));
}

.cesium-infoBox-title {
  background-color: rgba(23, 49, 71, 0.8);
}

/**cesium 任务栏的FPS信息*/
.cesium-performanceDisplay-defaultContainer {
  top: auto;
  bottom: 35px;
  right: 50px;
}

.cesium-performanceDisplay-ms,
.cesium-performanceDisplay-fps {
  color: #fff;
}

/**cesium tileset调试信息面板*/
.cesium-viewer-cesiumInspectorContainer {
  top: 10px;
  left: 10px;
  right: auto;
}

.cesium-cesiumInspector {
  background-color: rgba(23, 49, 71, 0.8);
}

/**覆盖mars内部控件的颜色等样式*/
.mars-compass .mars-compass-outer {
  fill: rgba(23, 49, 71, 0.8);
}

.mars-contextmenu-ul,
.mars-sub-menu {
  background-color: rgba(23, 49, 71, 0.8);

  > li > a:hover,
  > li > a:focus,
  > li > .active {
    background-color: var(--mars-hover-btn-bg, #3ea6ff);
  }

  > .active > a,
  > .active > a:hover,
  > .active > a:focus {
    background-color: var(--mars-hover-btn-bg, #3ea6ff);
  }
}

/* Popup样式*/
.mars-popup-color {
  color: var(--mars-text-color, #ffffff);
}

.mars-popup-background {
  background: var(--mars-bg-base, rgba(63, 72, 84, 0.9));
}

.mars-popup-content {
  margin: 15px;
}

.mars-popup-btn-custom {
  padding: 3px 10px;
  border: 1px solid #209ffd;
  background: #209ffd1c;
}

.mars-tooltip {
  color: var(--mars-text-color, #ffffff);
  background: var(--mars-bg-base, rgba(63, 72, 84, 0.9));
  border: 1px solid var(--mars-bg-base, rgba(63, 72, 84, 0.9));
}

.mars-tooltip-top:before {
  border-top-color: var(--mars-bg-base, rgba(23, 49, 71, 0.8));
}

.mars-tooltip-bottom:before {
  border-bottom-color: var(--mars-bg-base, rgba(23, 49, 71, 0.8));
}

.mars-tooltip-left:before {
  border-left-color: var(--mars-bg-base, rgba(23, 49, 71, 0.8));
}

.mars-tooltip-right:before {
  border-right-color: var(--mars-bg-base, rgba(23, 49, 71, 0.8));
}

/* all 中的html样式 */
.mars-template-titile {
  color: var(--mars-base-color);
  border-bottom: 1px solid var(--mars-hover-btn-bg);

  a {
    font-size: 16px;
    color: var(--mars-msg-title-color);
  }
}

.mars-template-content {
  label {
    padding-right: 6px;
  }

  input {
    color: var(--mars-text-color);
    background-color: transparent !important;
    padding: 4px 5px;
  }

  input::placeholder {
    color: #cdcdcd !important;
  }

  textarea {
    color: var(--mars-base-color);
    background-color: transparent !important;
    padding: 4px 5px;
  }

  textarea::placeholder {
    color: #cdcdcd !important;
  }
}
</style>
